<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\tool\Result;
use app\common\model\News as NewsModel;

class News extends Base
{

    /**
     * 新闻列表
     */
    public function getList()
    {
        try {
            $param = $this->request->param();
            $cate = $param['cate'];
            if(!in_array($cate,[1,2])){
                return Result::fail('参数错误');
            }
            $map = [
                'status' => 1,
                'cate' => $cate,
            ];
            $list = NewsModel::getPageList(
                $map,
                'id,title,cate,sub_title,images,create_time',
                $this->getPage(),
                $this->getLimit(),
                false,
            );
            foreach ($list['data'] as &$item) {
                if($item->cate == 2){
                    $item->create_times = date('Y-m',$item->getData('create_time'));
                    $item->day = date('d',$item->getData('create_time'));
                }else{
                    $item->create_times = date('Y-m-d',$item->getData('create_time'));
                }
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 课程章节详情
     */
    public function info()
    {
        try {
            $param = $this->request->param();
            $item = NewsModel::where('id', $param['id'])->field('id,title,cate,create_time,content,hits')->find();
            if (empty($item)) {
                return Result::fail('暂无详情');
            }
            $url = 'https://' . $_SERVER['SERVER_NAME'] . '/uploads/';
            $item->content = htmlspecialchars_decode(str_replace('/uploads/', $url, $item->content));
            $item->content = str_replace('\\', '', $item->content);
            $item->create_times = date('Y-m-d',$item->getData('create_time'));
            NewsModel::where('id', $param['id'])->inc('hits',1)->update();
            return Result::success('获取成功！', $item);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
